/*
 * TestNet.cpp
 *
 *  Created on: 2012-4-9
 *      Author: chenjialiang
 */

#include "TestNet.h"

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstdarg>
#include <unistd.h>
#include <cstring>
#include <cerrno>
#include <time.h>
#include <signal.h>
#include <cstdlib>

#include <SocketConnection.h>
#include <EventManager.h>
#include <FilterWordBase.h>

#include <Log.h>

using namespace std;

using namespace Zha;

event *pevent;
void ReadMsg(int fd, short event, void *args)
{
	Zha::EventManager& zm = Zha::EventManager::Instance();
	long *arg = (long*)args;
	cout<<"prepaare read"<<endl;
	Zha::SocketConnection *pconn = (Zha::SocketConnection*)arg[1];
	char buf[1024];
	pconn->Read(arg[0], buf, sizeof(buf));
	cout<<"ReadMsg:"<<buf<<endl;
	zm.AddEvent(pevent);
}

TestNet::TestNet()
{
	// TODO Auto-generated constructor stub

}

TestNet::~TestNet()
{
	// TODO Auto-generated destructor stub
}

void TestNet::main()
{
	Zha::EventManager& zm = Zha::EventManager::Instance();
	Zha::SocketConnection zhaConn;

	zhaConn.Init();
	Log("Init success");

	int clientSocket = zhaConn.Accept();
	if (clientSocket > 0)
	{
		long arg[2];
		Log("Accept success");

		arg[0] = clientSocket;
		arg[1] = (long)(void*)&zhaConn;
		pevent = zm.CreateReadEvent(clientSocket, ReadMsg, arg);
		zm.AddEvent(pevent);
		cout<<"begin dispatch"<<endl;
		zm.Dispatch();
	}
	else cout<<"accept fail"<<endl;
}
